"use strict";

var express = require('express');
var mysql = require('mysql')
var UUID = require('uuid')
var dt = require('date-utils')
var util = require('util')
var MyUtils = require('./../util/utils')
var connection = require('./../constant/mysqlconnection').connection
var DeleteAction = require('./app/delete-app')


var router = express.Router();
var myUtils = new MyUtils()
var deleteAction = new DeleteAction()

// 添加路由操作
router.post('/regist', function (req, res) {
    // 查询数据库，判断当前用户是否存在
    // 检验合法性 插入数据库
    // console.log('req :' + util.inspect(req.body, true))
    // var userJSONObj = JSON.parse()
    searchUserByAccount(connection, req.body.account, function (searchError, searchResult) {
        if (!searchError && !myUtils.isEmptyObj(searchResult)) {
            var bizErrorModel = myUtils.generateSuccess()
            bizErrorModel.model = {
                success: 1,
                info: '该账号已注册'
            }
            res.end(JSON.stringify(bizErrorModel))
        } else {
            var addSql = 'INSERT INTO user(user_id,user_account,user_pwd,create_time,logic_delete_flag) VALUES(?,?,?,?,\'01\')';
            var addSqlParams = [UUID.v1(), req.body.account, req.body.password, new Date().toFormat('YYYY-MM-DD HH24:MI:SS')];
            connection.query(addSql, addSqlParams, function (err, results, fields) {
                if (!err) {
                    var bizSucModel = myUtils.generateSuccess()
                    bizSucModel.model = {
                        success: 0,
                        info: '注册成功'
                    }
                    res.end(JSON.stringify(bizSucModel))
                } else {
                    res.end(JSON.stringify(myUtils.generateInnerError()))
                }
            })
        }
    })
})

router.post('/login', function (req, res) {
    var searchSql = 'SELECT * FROM user WHERE user_account = ? AND user_pwd = ? AND logic_delete_flag = 01'
    var searchSqlParams = [req.body.account, req.body.password]
    connection.query(searchSql, searchSqlParams, function (err, result) {
        if (!err) {
            var bizSucModel = myUtils.generateSuccess()
            if (!myUtils.isEmptyObj(result)) {
                bizSucModel.model = {
                    success: 0,
                    userid: result[0].user_id
                }
            } else {
                bizSucModel.model = {
                    success: 1,
                    info: '账号或密码错误'
                }
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.get('/list', function (req, res) {
    // 分页查询数据库
    // 由于数据量不大，直接使用原生sql 进行查询
    // var searchSql = 'SELECT * FROM user LIMIT ' + (parseInt(req.query.page) - 1) + ',' + req.query.size
    var searchSql = 'SELECT * FROM user WHERE logic_delete_flag = 01 ORDER BY create_time DESC LIMIT ' + (parseInt(req.query.page) - 1) + ',' + req.query.size
    connection.query(searchSql, function (err, results) {
        if (!err) {
            // console.log(util.isArray(results)) -> true
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                user_list: results
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.delete('/deleteUser', function (req, res) {
    // 逻辑删除用户
    //UPDATE `user` SET logic_delete_flag = '01' WHERE user_account = 'wusea@foxmail.cn'
    var updateSql = 'UPDATE user SET logic_delete_flag = 99 WHERE user_id = ?'
    var updateSqlParam = [req.body.userId]
    connection.query(updateSql, updateSqlParam, function (err, result) {
        if (!err) {
            if (result.affectedRows == 0) {
                // 说明当前用户不存在
                var bizSucModel = myUtils.generateSuccess()
                bizSucModel.model = {
                    success: 2,
                    info: '用户不存在'
                }
                res.end(JSON.stringify(bizSucModel))
            } else {
                deleteUserApp(req, res)
            }
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

function deleteUserApp(req, res) {
    var searchSql = 'select id from application where user_id = ? and logic_delete_flag = 01'
    var searchSqlParams = [
        req.body.userId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            if (results.length > 0) {
                for (var i = 0, len = results.length; i < len; i++) {
                    req.body.appId = results[i].id
                    deleteAction.deleteApp(req, res)
                }
            } else {
                var bizSucModel = myUtils.generateSuccess()
                bizSucModel.model = {
                    success: 0,
                    info: '删除成功'
                }
                res.end(JSON.stringify(bizSucModel))
            }
        } else {
            console.log(error)
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
}


router.put('/updateUserPwd', function (req, res) {
    // 更新用户密码
    var updateSql = 'UPDATE user SET user_pwd = ? WHERE user_account = ? AND logic_delete_flag = 01'
    var updateSqlParam = [req.body.password, req.body.account]
    connection.query(updateSql, updateSqlParam, function (err, result) {
        if (!err) {
            var bizSucModel = myUtils.generateSuccess()
            if (result.affectedRows) {
                bizSucModel.model = {
                    success: 0,
                    info: '密码重置成功'
                }
            } else {
                bizSucModel.model = {
                    success: 1,
                    info: '用户未找到'
                }
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

/**
 * 根据邮箱查询用户
 * @param connection
 * @param account
 * @param callback
 */
function searchUserByAccount(connection, account, callback) {
    // 是否加上 AND logic_delete_flag = 01
    var searchSql = 'SELECT * FROM user WHERE user_account = ?'
    var searchSqlParam = [account]
    connection.query(searchSql, searchSqlParam, function (err, res) {
        if (!err) {
            callback(null, res)
        } else {
            callback(err, null)
        }
    })
}

module.exports = router


